/**
 * 借鉴mint-ui实现点击控件外部的操作
 * https://github.com/ElemeFE/mint-ui/blob/8ed48e3bfd7a9d5d05198b7515fd6da0ccd89c87/src/utils/clickoutside.js
 * exp: <div v-clickOutSide:event=""></div>
 */

const clickoutsideContext = 'zhihu-clickOutSide';

export default {
	bind (el, binding, vnode) {
		const documentHandler = function (e) {
			if (vnode.context && !el.contains(e.target)) {
				vnode.context[el[clickoutsideContext].methodName]();
			}
		};
		el[clickoutsideContext] = {
			documentHandler,
			methodName: binding.expression,
			arg: binding.arg || 'click'
		};
		document.addEventListener(el[clickoutsideContext].arg, documentHandler);
	},
	update (el, binding) {
		el[clickoutsideContext].methodName = binding.expression;
	},
	unbind (el) {
		document.removeEventListener(
			el[clickoutsideContext].arg,
			el[clickoutsideContext].documentHandler);
	}
};
